#include "MarsPrecompile.h"

#include "MarsRenderTarget.h"
#include "MarsRenderer.h"

using namespace Graphics;

bool RenderTarget::Create()
{
	D3D11_TEXTURE2D_DESC texDesc;
	texDesc.Width     = m_iWidth;
	texDesc.Height    = m_iHeight;
	texDesc.MipLevels = 1;
	texDesc.ArraySize = 1;
	texDesc.Format    = DXGI_FORMAT_R24G8_TYPELESS;
	texDesc.SampleDesc.Count   = 1;  
	texDesc.SampleDesc.Quality = 0;  
	texDesc.Usage          = D3D11_USAGE_DEFAULT;
	texDesc.BindFlags      = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE;
	texDesc.CPUAccessFlags = 0; 
	texDesc.MiscFlags      = 0;

	ID3D11Texture2D* depthMap = 0;
	HRESULT hr = Renderer::Instance().GetDevice()->CreateTexture2D( &texDesc, 0, &depthMap );

	if ( FAILED( hr ) )
		return false;

	D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
	dsvDesc.Flags = 0;
	dsvDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	dsvDesc.Texture2D.MipSlice = 0;
	
	hr = Renderer::Instance().GetDevice()->CreateDepthStencilView( depthMap, &dsvDesc, &m_pDepthMapDSV );

	if ( FAILED( hr ) )
	{
		SAFE_RELEASE( depthMap );
		Delete();
		return false;
	}

	D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
	srvDesc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
	srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	srvDesc.Texture2D.MipLevels = texDesc.MipLevels;
	srvDesc.Texture2D.MostDetailedMip = 0;
	
	Renderer::Instance().GetDevice()->CreateShaderResourceView( depthMap, &srvDesc, &m_pDepthMapSRV );

	SAFE_RELEASE( depthMap );

	if ( ( FAILED( hr ) ) )
	{
		Delete();
		return false;
	}

	return true;
}

void RenderTarget::Delete()
{
	SAFE_RELEASE( m_pDepthMapSRV );
	SAFE_RELEASE( m_pDepthMapDSV );
}

void RenderTarget::Bind()
{
	ID3D11DeviceContext* dc = Renderer::Instance().GetDeviceContext();
	dc->RSSetViewports(1, &m_viewport);

	ID3D11RenderTargetView* renderTargets[ 1 ] = { 0 };
	dc->OMSetRenderTargets( 1, renderTargets, m_pDepthMapDSV );
	dc->ClearDepthStencilView( m_pDepthMapDSV, D3D11_CLEAR_DEPTH, 1.0f, 0 );
}
